import { useEffect } from 'react';
import { View, Text, ImageBackground, Image, TextInput, StyleSheet, Pressable, ActivityIndicator } from 'react-native';
import { router } from 'expo-router'
import AntDesign from '@expo/vector-icons/AntDesign';

import CommonServer from './../common/service/CommonServer';
import { useSetState, useCurrent } from './../common/hooks/index'
import * as FORM from "./../components/Form"
import { CFlex, CColor } from './../constant/css'
import util from './../common/utils/util';
import Constant from '../constant/Constant';
import IP from '../common/http/host';
import { StatusBar } from 'expo-status-bar';

export default function Login() {
    const [state, setState] = useSetState({
        phone: '',
        password: '',
        code: '',
        codeImg: '',
        codeText: '',
        rememberMe: false,

        isLoading: false,
    })
    const [ref, setRef] = useCurrent({
        phone: '',
        password: '',
        code: '',
    })

    useEffect(() => {
        loadLocalInfo()
    }, [])

    const loadLocalInfo = async () => {
        const userInfo = await util.getLocalStore(Constant.LOGIN_TOKEN_KEY)
        const token = userInfo?.token || ''
        if (!token) return loadLoginCode()
        return goHome()
    }

    const loadLoginCode = async () => {
        const [err, res] = await CommonServer.loadLoginCode()
        if (err) return util.showInfo(err)
        const _ = res.data || {}
        const svgStr = _.data.replace(/\\/g, '')
        const result = 'data:image/svg+xml;base64,' + util.encodeBase64(svgStr)
        if (util.isDev()) {
            return setState({
                codeImg: result,
                codeText: _.text,
                phone: '13658082692',
                password: '123456',
                code: _.text,
            })
        }
        setState({
            codeImg: result,
            codeText: _.text,
        })
    }

    const doLogin = async () => {
        const { phone: mobile, password, code: _code, codeText, rememberMe } = state
        const code = _code.replace(' ', '')
        if (!mobile) return util.showInfo('请输入手机号~')
        if (!password) return util.showInfo('请输入密码~')
        if (!code) return util.showInfo('请输入验证码~')
        if (codeText !== code) return util.showInfo('验证码错误~')
        setState({ isLoading: true })
        const params = {
            mobile,
            password,
            code,
            uuid: codeText,
        }
        const [err, res] = await CommonServer.doLogin(params)
        if (err) {
            setState({ isLoading: false })
            return util.showInfo(err)
        }
        const userInfo = res.data || null
        util.setLocalStore(Constant.LOGIN_TOKEN_KEY, userInfo)
        const loginInfo = {
            rememberMe,
            mobile,
            password: rememberMe ? util.encodeBase64(password) : ""
        }
        util.setLocalStore(Constant.LOGIN_INFO, loginInfo)
        return goHome()
    }

    const goHome = () => router.replace('/home')
    const testHome = () => {
        // router.push('/product/productDetail')
        // router.setParams({ id: '50e276eaa48d44e7bff766458130a991' })
    }

    return (
        <ImageBackground
            source={require('./../assets/login_bg.jpg')}
            style={{ height: '100%', width: '100%' }}
            resizeMode='cover'
        >
            <StatusBar translucent />
            <View style={{ height: 50 }} />
            <View style={{ flex: 1, ...CFlex.cc }}>
                <Pressable onPress={testHome}>
                    <Image style={styles.logo} source={require('./../assets/favicon.png')} />
                </Pressable>
                <View style={styles.input_contain}>
                    <View style={styles.input_icon}>
                        <AntDesign name="mobile1" size={24} color="black" />
                    </View>
                    <View style={{ flex: 1 }}>
                        <TextInput
                            ref={(v) => setRef({ phone: v })}
                            style={styles.input}
                            onChangeText={newText => {
                                if (newText.length === 11) {
                                    ref.password?.focus?.()
                                }
                                setState({ phone: newText })
                            }}
                            onSubmitEditing={e => {
                                ref.password?.focus?.()
                            }}
                            value={state.phone}
                            placeholderTextColor={CColor.Black}
                            selectionColor={CColor.Black}
                            placeholder="请输入手机号码"
                            textAlign="center"
                            keyboardType='phone-pad'
                            returnKeyType="next"
                        />
                    </View>
                </View>
                <View style={[styles.input_contain, { marginTop: 40 }]}>
                    <View style={styles.input_icon}>
                        <AntDesign name="lock" size={28} color="black" />
                    </View>
                    <View style={{ flex: 1 }}>
                        <TextInput
                            ref={(v) => setRef({ password: v })}
                            style={styles.input}
                            onChangeText={newText => {
                                setState({ password: newText })
                            }}
                            onSubmitEditing={e => {
                                ref.code?.focus?.()
                            }}
                            value={state.password}
                            placeholderTextColor={CColor.Black}
                            selectionColor={CColor.Black}
                            secureTextEntry={true}
                            placeholder="请输入密码"
                            textAlign="center"
                            returnKeyType="next"
                        />
                    </View>
                </View>
                <View style={[styles.input_contain, { marginTop: 40 }]}>
                    <View style={[styles.input_icon, { left: 25 }]}>
                        <AntDesign name="mail" size={20} color="black" />
                    </View>
                    <View style={{ flex: 1 }}>
                        <TextInput
                            ref={(v) => setRef({ code: v })}
                            style={[styles.input, { paddingRight: 10, paddingLeft: 30 }]}
                            onChangeText={newText => {
                                setState({ code: newText })
                            }}
                            onSubmitEditing={e => {
                                doLogin()
                            }}
                            value={state.code}
                            placeholderTextColor={CColor.Black}
                            selectionColor={CColor.Black}
                            placeholder="验证码"
                            textAlign="center"
                            returnKeyType="next"
                        />
                    </View>
                    {state.codeImg ?
                        <Pressable onPress={loadLoginCode}>
                            <FORM.ExpoImage contentFit='contain' style={styles.code_img} source={state.codeImg} />
                        </Pressable>
                        :
                        <View style={[CFlex.cc, { width: styles.code_img.width }]} >
                            <ActivityIndicator size={23} color={CColor.Black} />
                        </View>
                    }
                </View>
                <View style={[{ marginTop: 40, width: '100%' }]}>
                    <FORM.Button
                        label='登 录'
                        isLoading={state.isLoading}
                        style={{
                            marginHorizontal: 20,
                            borderRadius: 50,
                            height: 60,
                        }}
                        onClick={doLogin}
                    />
                </View>
                <View style={{ height: 120 }} />
            </View>
        </ImageBackground>
    );
}

const styles = StyleSheet.create({
    logo: {
        width: 100,
        height: 100,
        borderRadius: 100,
        marginBottom: 30,
    },
    input_contain: {
        marginHorizontal: 20,
        ...CFlex.row,
        ...CFlex.sc,
        borderColor: CColor.Black,
        borderWidth: 1,
        borderRadius: 50,
        height: 60,
        overflow: 'hidden',
    },
    input_icon: {
        position: 'absolute',
        left: 20,
        height: 60,
        ...CFlex.row,
        ...CFlex.cc,
    },
    input: {
        height: '100%',
        paddingHorizontal: 15,
        textAlign: 'center',
        fontSize: 18,
        color: CColor.Black,
        // fontWeight: 'bold',
        letterSpacing: 2,
    },
    code_img: {
        width: 120,
        height: 60,
        backgroundColor: CColor.White,
    },
});
